package com.sduept.nwld.mobile.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.core.ParamManager;
import com.sduept.core.entity.SystemParameter;
import com.sduept.message.entity.AlarmMessage;
import com.sduept.nwld.dataserver.model.rota.RotaPerson;
import com.sduept.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 手机端消息推送
 * @author Ningfw
 * @date 20171020
 *
 */

@Service
public class MessagePushManager {

	@Autowired
	private ParamManager pc;
	
	@Autowired
	private MobileUserInfoManager mobileUserInfoManager;
	
	/**
	 * 异常告警消息推送
	 * @param alarmList
	 * @return
	 */
	public void alarmMessagePush(final List<AlarmMessage> alarmList){
		
		try {
			new Thread(){
				@Override
				public void run() {
					
					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
					String receivedUser = getReceivedUser();
			        nvps.add(new BasicNameValuePair("loginId", receivedUser));//zhengmr@csg.cn,yujiang@csg.cn
			        JSONArray jsa = new JSONArray();
			        Set<SystemParameter> apptypes = getAppAlarmTypes();
			        for(int i = 0; i < alarmList.size(); i++){
			        	Date createT = alarmList.get(i).getCreateTime();
			            String createTime = DateUtil.getStringDate(createT, DateUtil.pattern_ymdhms);
			            JSONObject jso = new JSONObject();
			            SystemParameter param= pc.get(alarmList.get(i).getMsgType());
			            if(!apptypes.contains(param)) {
			            	continue;
			            }
			            jso.put("title", param.getDescription());
			            jso.put("summary",  createTime + "  " + alarmList.get(i).getContent());
			            jso.put("scheme", alarmList.get(i).getId());
			            jsa.add(jso);
			        }
			        if(jsa.size()>0) {
			        	 nvps.add(new BasicNameValuePair("events", jsa.toString()));
					     messagePush(nvps);
			        }
			       
				}
			}.start();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	private Set<SystemParameter> getAppAlarmTypes(){
		Set<SystemParameter> rtns = new HashSet<>();
		String pushmsgs = pc.get(ParamDesc.MOBILE_APP_PUSH_ALARMS).getValue();
		if(StringUtils.isNoneEmpty(pushmsgs)) {
			String[] ids = pushmsgs.split(",");
			for(int i = 0; i < ids.length; i++){
				rtns.add(pc.get(ids[i]));
			}
		}
		return rtns;
	}
	/**
	 * 异常告警消息推送
	 * @param alarmMessage
	 */
	public void alarmMessagePush(AlarmMessage alarmMessage){
		
		Date timeDiff = gainTimeDifference();//当前时间减去时间差
		if(null != timeDiff && !"".equals(timeDiff)){
			
			if(alarmMessage.getCreateTime().after(timeDiff)){//故障时间在时间差内
				
				List<AlarmMessage> alarmList = new ArrayList<AlarmMessage>();
				alarmList.add(alarmMessage);
				alarmMessagePush(alarmList);
			}
		}
	}
	
	/**
	 * 故障报告消息推送
	 * @param cimList
	 * @return
	 */
	public void faultReportPush(final List<FaultRecord> cimList){
		
//		try {
//			new Thread(){
//				@Override
//				public void run() {
//					
//					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//					String receivedUser = getReceivedUser();
//			        nvps.add(new BasicNameValuePair("loginId", receivedUser));//zhengmr@csg.cn,yujiang@csg.cn
//			        JSONArray jsa = new JSONArray();
//			        for(int i = 0; i < cimList.size(); i++){
//			            JSONObject jso = new JSONObject();
//			            jso.put("title", cimList.get(i).getEquipment());
//			            String faultReason = cimList.get(i).getFaultReson();
//			            Date faultT = cimList.get(i).getFaultTime();
//			            String faultTime = DateUtil.getStringDate(faultT, DateUtil.pattern_ymdhms);
//			            if(faultReason != null){
//			            	jso.put("summary", faultTime + "  " + faultReason);
//			            }else{
//			            	jso.put("summary", faultTime);
//			            }
//			            jso.put("scheme", cimList.get(i).getEquipment_id());
//			            jsa.add(jso);
//			        }
//			        nvps.add(new BasicNameValuePair("events", jsa.toString()));
//			        messagePush(nvps);
//				}
//			}.start();
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
	}
	
	/**
	 * 故障报告消息推送
	 * @param faultRecord
	 */
	public void faultReportPush(FaultRecord faultRecord){
		
//		Date timeDiff = gainTimeDifference();//当前时间减去时间差
//		if(null != timeDiff && !"".equals(timeDiff)){
//			
//			if(faultRecord.getFaultTime().after(timeDiff)){//故障时间在时间差内
//
//				List<FaultRecord> cimList = new ArrayList<FaultRecord>();
//				cimList.add(faultRecord);
//				faultReportPush(cimList);
//			}
//		}
	}
	
	/**
	 * 值班消息消息推送
	 * @param rotaPerson
	 */
	public void rotaPersonPush(RotaPerson rotaPerson){
		
		rotaPersonMessPush(rotaPerson);
	}
	
	/**
	 * 值班消息消息推送
	 * @param rotaPerson
	 * @return
	 */
	private void rotaPersonMessPush(final RotaPerson rotaPerson){
		
		try {
			new Thread(){
				@Override
				public void run() {
					
					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
					String receivedUser = getRecUserByCode(rotaPerson.getPersonId());
			        nvps.add(new BasicNameValuePair("loginId", receivedUser));//zhengmr@csg.cn,yujiang@csg.cn
			        JSONArray jsa = new JSONArray();
		            JSONObject jso = new JSONObject();
		            jso.put("title", "值班人："+rotaPerson.getPersonName());
	            	jso.put("summary", "值班日期："+rotaPerson.getRotaDate());
		            jso.put("scheme", rotaPerson.getPersonId());
		            jsa.add(jso);
			        nvps.add(new BasicNameValuePair("events", jsa.toString()));
			        messagePush(nvps);
				}
			}.start();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取全部消息接收人
	 * @return
	 */
	public String getReceivedUser(){
		
		String receivedUser = "";
//		List<MobileUserInfo> userList = mobileUserInfoManager.findReceivedUser();
//		for(MobileUserInfo mu : userList){
//			
//			receivedUser += "," + mu.getAccount();
//		}
//		if(receivedUser != null && (!receivedUser.equals(""))){
//			
//			receivedUser = receivedUser.replaceAll(" ", "").substring(1);
//		}
		
		return receivedUser;
	}
	
	/**
	 * 根据code获取消息接收人
	 * @param userCode
	 * @return
	 */
	public String getRecUserByCode(String userCode){
		
		String receivedUser = "";
//		List<MobileUserInfo> userList = mobileUserInfoManager.findRecUserByCode(userCode);
//		for(MobileUserInfo mu : userList){
//			
//			receivedUser += "," + mu.getAccount();
//		}
//		if(receivedUser != null && (!receivedUser.equals(""))){
//			
//			receivedUser = receivedUser.replaceAll(" ", "").substring(1);
//		}
		
		return receivedUser;
	}
	
	/**
	 * 获取当前时间减去时间差后的时间
	 * @return
	 */
	public Date gainTimeDifference(){
		
		Date timeDiff = null;
		String timeDifference = pc.get(ParamDesc.NWLD_MOBILE_TIME_DIFFERENCE).getValue();//移动端消息推送时间差
		if(null != timeDifference && !"".equals(timeDifference)){
			
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - Integer.parseInt(timeDifference));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String strDiff = sdf.format(calendar.getTime());
			try {
				timeDiff = sdf.parse(strDiff);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		return timeDiff;
	}
	
	/**
	 * 消息推送
	 * @param nvps 所传参数
	 * @return
	 */
	public String messagePush(List<NameValuePair> nvps){
		
		String strResult = "";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String nwldMobileUrl = pc.get(ParamDesc.NWLD_MOBILE_URL).getValue();//手机端服务器地址
//		HttpPost httpPost = new HttpPost("http://127.0.0.1:8001/process/service/nwld-mobile/sendmsg.do");
		HttpPost httpPost = new HttpPost(nwldMobileUrl);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
			.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000)
			.setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			HttpResponse response = httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == 200){
				strResult = EntityUtils.toString(response.getEntity());
			}else{
				strResult = "Error Response:" + response.getStatusLine().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(null != httpClient){
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return strResult;
	}
}
